const glob = require("glob");
const path = require("path");
const fs = require("fs-extra");

glob("src/**/*.ts", (err, filenames) => {
  // console.log(filenames)
  filenames.forEach(async filename => {
    var dir = path.dirname(filename);
    var content = await fs.readFile(filename, "utf8");
    var hasObj = false;
    content = content
      .replace(/ "@([^"]+)"/g, (_, _path) => {
        var _dir = path.join("src", path.dirname(_path));
        var _name = path.basename(_path);
        var _dst = path.relative(dir, _dir).replace(/\\/g, "/");
        if (/^\w/.test(_dst)) {
          _dst = "./" + _dst;
        } else if (/^\//.test(_dst)) {
          _dst = "." + _dst;
        }
        return ` "${_dst}/${_name}"`;
      })
      .replace(/ extends Object\b/, () => {
        hasObj = true;
        return "";
      })
      .replace(/( from ")\//g, "$1./");
    if (hasObj) {
      content = content.replace("super();", "");
    }
    content = content.replace(/ constructor\(\)\s+\{\s+return;\s+\}/, " ");
    if (/ extends /.test(content)) {
      if (!/\bsuper\(/.test(content)) {
        content = content.replace(
          /( constructor\([^)]*\)\s+\{\s+)/,
          "$1super();"
        );
      } /*  else {
        content = content.replace(/super\(\);(super\()/, "$1");
      } */
    } else {
      content = content.replace(/super\(\);/, "");
    }
    if (path.basename(filename).startsWith("AMI_")) {
      content = content
        // .replace(/^undefined/g, "")
        .replace(
          /(;\s+)(userObject = arg3;\s+)(callFunction = )/,
          "$1this.$2this.$3"
        )
        .replace(
          /\(null != _response\)(\s+\{\s+)(_response.call)/,
          `(this._response) $1this.$2`
        )
        .replace(
          /arg1: Function=null,\s+arg2: Function=null,\s+arg3: Object=null/,
          // "arg1?: Function, arg2?: Function, arg3:any",
          "arg1?: Function, arg2?: Function, arg3?: any"
        )
        .replace(/ (?=cdeException\(new Exception\()/, " this.");
    }
    fs.writeFile(filename, content);
  });
});
